package com.ywy.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ywy.model.GroupForm;
import com.ywy.model.addressList;
import com.ywy.config.JDBC;

public class GroupServlet extends HttpServlet {

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	
		String action = request.getParameter("action"); // 获取action参数的值
		if ("query".equals(action)) {
			this.query(request, response); // 查询通讯组列表
		} else if ("query_add".equals(action)) {	//添加联系人时查询通讯组信息
			this.query_add(request, response);
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}

	public void query(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setAttribute("groupList", queryGroup());	// 获取通讯组列表并保存到HttpServletRequest中
		request.getRequestDispatcher("left.jsp").include(request, response);	//转发页面
	}

	public void query_add(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setAttribute("groupList", queryGroup());	// 获取通讯组列表并保存到HttpServletRequest中
		request.getRequestDispatcher("linkmanAdd.jsp").forward(request, response);
	}
	public List queryGroup(){
		JDBC conn = new JDBC();	//创建数据库连接对象
		String sql = "SELECT * FROM tb_group";
		ResultSet rs = conn.executeQuery(sql); // 查询通讯组
		List list = new ArrayList();
		try {
			while (rs.next()) {
				GroupForm f = new GroupForm();
				f.setId(rs.getInt(1));		//获取通讯组ID
				f.setName(rs.getString(2));	//获取通讯组名称
				list.add(f); // 将通讯组添加到List集合中
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			conn.close();	//关闭数据库连接
		}	
		return list;
	}
}
